<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>管理个人博客</title>
        <meta name="renderer" content="webkit">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <link rel="stylesheet" href="../source/layui/css/layui.css" media="all">
    </head>
    <body>
        <table class="layui-hide" id="test" lay-filter="test"></table>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
<!--                <button class="layui-btn layui-btn-sm" id="select" lay-event="all">全选</button>-->
                <button class="layui-btn layui-btn-sm" lay-event="save">保存</button>
                <button class="layui-btn layui-btn-sm" lay-event="delete">删除</button>
            </div>
        </script>

        <script type="text/html" id="barDemo">
            <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">查看</a>
            <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
        </script>


        <script src="../source/js/jquery-3.4.1.min.js" type="text/javascript"></script>
        <script src="../source/layui/layui.js" type="text/javascript"></script>
        <script src="../../js/axios.min.js" type="text/javascript"></script>

        <!-- 修改日期格式 -->
        <script type="text/html" id="cTime">
            {{#
            Date.prototype.toString = function () {
            return this.getFullYear() + "-" + (this.getMonth() + 1) + "-" + this.getDate()
            + " " +this.getHours() +":" +this.getMinutes() + ":" + this.getSeconds();
            };
            }}
            {{
            new Date(d.releaseDate)
            }}
        </script>

        <script>
            var blogType = {};//博客类型
            axios.get("http://localhost:8081/kun/admin/blogType/selectBlogType").then(res=>{
                blogType = res.data.data.blogTypes;
            })

            //选择博客类型
            function selectBlogTypeName(d) {
                var html =
                    '<select name="type" lay-filter="type" lay-search="true">' +
                    '<option disabled>请选择博客类型</option>';
                $(blogType).each(function (index) {
                    var val = index+1;
                    html += '<option value="'+val+'" '+(d.typeId === val ? 'selected=""':'')+'>'+blogType[index].typeName+'</option>';
                })
                html += '</select>';
                return html;
            }


            layui.use(['table','form'], function () {
                var table = layui.table;
                var form = layui.form;

                table.render({
                    elem: '#test'
                    , url: 'http://localhost:8081/kun/admin/index/queryPage'
                    , method: "post"
                    , limit: 10
                    , cellMinWidth: 80 //全局定义常规单元格的最小宽度
                    , toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
                    , defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
                        title: '提示'
                        , layEvent: 'LAYTABLE_TIPS'
                        , icon: 'layui-icon-tips'
                    }]
                    , title: '用户数据表'
                    , cols: [[
                        {type: 'checkbox', fixed: 'left'}
                        , {field: 'id', title: 'ID', fixed: 'left', unresize: true, sort: true}
                        , {field: 'title', title: '标题', event: 'setTitle',}
                        , {field: 'releaseDate', title: '发布日期', sort: true, toolbar: '#cTime'}
                        , {field: 'typeId', title: '博客类型', event: 'setTypeName',templet:function (d) {
                                return selectBlogTypeName(d);//选择博客类型
                            }}
                        , {fixed: 'right', title: '操作', toolbar: '#barDemo'}
                    ]]
                    , page: true
                    , done: function(res, curr, count){
                        //数据渲染完的回调。
                        //由于layui 设置了超出隐藏，所以这里改变下，以兼容操作按钮的下拉菜单
                        $(".layui-table-body, .layui-table-box, .layui-table-cell").css('overflow', 'visible');
                        $('td .layui-form-select').css('margin-top','-10px').css('margin-left','-15px').css('margin-right','-15px');
                    }
                    ,parseData: function(res){//返回的数据

                    }
                });

                //头工具栏事件
                table.on('toolbar(test)', function(obj){
                    var checkStatus = table.checkStatus(obj.config.id);
                    var data = checkStatus.data;//返回的数组
                    switch(obj.event){
                        case 'save': //保存
                            if(data.length > 0){
                                layer.confirm('确定要保存吗', function (index) {
                                    //前端后端 数组并不能交互
                                    //所以需要将数组 转换为json格式的字符串
                                    var blogs = JSON.stringify(data);
                                    axios.post("http://localhost:8081/kun/admin/blog/batchUpdateBlog",{blogs}).then(res=>{
                                        if(res.data.code === 200){
                                            layer.msg("保存成功!");
                                        }else {
                                            layer.alert('保存失败', {
                                                icon: 5,
                                                title: "提示"
                                            });
                                        }
                                    })
                                });
                            }else {
                                layer.alert('至少一个的哦', {
                                    icon: 5,
                                    title: "提示"
                                });
                            }
                            break;
                        case 'delete'://删除
                            if(data.length > 0){
                                layer.confirm('确定要删除吗', function (index) {
                                    var blogs = JSON.stringify(data);
                                    axios.post("http://localhost:8081/kun/admin/blog/batchDeleteBlog",{blogs}).then(res=>{
                                        if(res.data.code === 200){
                                            layer.msg("删除成功!");
                                            location.reload();//页面刷新
                                        }else {
                                            layer.alert('删除失败', {
                                                icon: 5,
                                                title: "提示"
                                            });
                                        }
                                    })
                                });
                            }else {
                                layer.alert('至少一个的哦', {
                                    icon: 5,
                                    title: "提示"
                                });
                            }
                            break;
                        case 'all'://全选
                            // var all = $('#select');//全选或取消全选
                            var flag = true;
                            $(".layui-form-checkbox").each(function() {
                                if (flag) {
                                    // all.html("全不选");
                                    $(this).addClass('layui-form-checked')
                                } else {
                                    $(this).removeClass('layui-form-checked')
                                }
                            });
                            break;
                        //自定义头工具栏右侧图标 - 提示
                        case 'LAYTABLE_TIPS':
                            layer.alert('这是工具栏右侧自定义的一个图标按钮');
                            break;
                    };
                });

                //监听行工具事件
                table.on('tool(test)', function (obj) {
                    var blog = obj.data;//获取数据
                    if (obj.event === 'detail') {//进行查看
                        window.open("../foreign/blog/view.html?id="+blog.id);//打开一个网页
                    }
                    else if (obj.event === 'del') {//进行删除
                        layer.confirm('真的删除行么', function (index) {
                            var id = blog.id;
                            axios.post("http://localhost:8081/kun/admin/index/del", {id}).then(res => {
                                if (res.data.code == 200) {
                                    layer.msg("删除成功");
                                    location.reload();
                                }else {
                                    layer.alert('删除失败', {
                                        icon: 5,
                                        title: "提示"
                                    });
                                }
                            });
                        });
                    }
                    else if (obj.event === 'edit') { //进行编辑
                        window.parent.openTab("修改博客"+blog.title,"writeBlog.html?id="+blog.id,"icon-writeblog");
                    }
                    else if (obj.event === 'setTitle') { //对表中标题进行编辑
                        layer.prompt({
                            formType: 2
                            , title: '修改 ID 为 [' + blog.id + '] 的博客标题'
                            , value: blog.title
                        }, function (value, index) {
                            blog.title = value;//更改标题
                            axios.post("http://localhost:8081/kun/admin/blog/updateBlogById",blog).then(res=>{
                                if (res.data.code == 200) {
                                    layer.msg("更新成功");
                                    layer.close(index);
                                }else {
                                    layer.alert('更新失败', {
                                        icon: 5,
                                        title: "提示"
                                    });
                                }
                            })

                            //同步更新表格和缓存对应的值
                            obj.update({
                                sign: value
                            });
                        });
                    }
                });

                // 监听下拉框选择事件修改表格缓存 type为name属性值
                form.on('select(type)', function (data) {
                    var selectElem = $(data.elem);
                    var tdElem = selectElem.closest('td');
                    var trElem = tdElem.closest('tr');
                    var tableView = trElem.closest('.layui-table-view');
                    //将最终的数据缓存给layui
                    table.cache[tableView.attr('lay-id')][trElem.data('index')][tdElem.data('field')] = data.value;
                });
            });
        </script>
    </body>
</html>